package com.weir.quarkus.commons.utils;
import java.util.Random;

public class SFExpressNumberGenerator {
    public static void main(String[] args) {
        String sfExpressNumber = generateSFExpressNumber();
        System.out.println("生成的顺丰快递单号为：" + sfExpressNumber);
    }

    public static String generateSFExpressNumber() {
        // 定义顺丰快递单号的前缀
        String prefix = "SF";
        
        // 生成随机的地区码
        String regionCode = generateRandomRegionCode();
        
        // 生成随机的序列号
        String sequenceNumber = generateRandomSequenceNumber();
        
        // 生产校验码
        String checkCode = generateCheckCode(regionCode + sequenceNumber);
        
        // 合并前缀、地区码、序列号和校验码，生成完整的顺丰快递单号
        String sfExpressNumber = prefix + regionCode + sequenceNumber + checkCode;
        
        return sfExpressNumber;
    }
    
    public static String generateRandomRegionCode() {
        // 定义可选的地区码字符集
        String chars = "0123456789";
        
        // 生成随机的地区码，长度为3
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        
        for (int i = 0; i < 3; i++) {
            int index = random.nextInt(chars.length());
            sb.append(chars.charAt(index));
        }
        
        return sb.toString();
    }
    
    public static String generateRandomSequenceNumber() {
        // 定义可选的序列号字符集
        String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        
        // 生成随机的序列号，长度为9
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        
        for (int i = 0; i < 9; i++) {
            int index = random.nextInt(chars.length());
            sb.append(chars.charAt(index));
        }
        
        return sb.toString();
    }
    
    public static String generateCheckCode(String numberWithoutCheckCode) {
        // 计算校验码
        int[] weightArray = {1, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41};
        int sum = 0;
        
        for (int i = 0; i < numberWithoutCheckCode.length(); i++) {
            char ch = numberWithoutCheckCode.charAt(i);
            int weight = weightArray[i % weightArray.length];
            int value = Character.isDigit(ch) ? ch - '0' : ch - 'A' + 10;
            sum += weight * value;
        }
        
        int checkCodeValue = 10 - (sum % 10);
        String checkCode = Integer.toString(checkCodeValue);
        
        return checkCode;
    }
}